const { TosClient, TosClientError, TosServerError } = require('@volcengine/tos-sdk');

class VolcUploader {
    constructor() {
        // 初始化火山引擎 TOS 客户端
        
        this.client = new TosClient({
            accessKeyId: process.env.VOLC_ACCESS_KEY_ID,
            accessKeySecret: process.env.VOLC_SECRET_KEY,
            region: process.env.VOLC_REGION,
            endpoint: 'tos-cn-beijing.volces.com',
        });
        this.bucket = process.env.VOLC_BUCKET;
    }

    /**
     * 处理 TOS 错误
     * @private
     */
    handleError(error) {
        if (error instanceof TosClientError) {
            console.log('Client Err Msg:', error.message);
            console.log('Client Err Stack:', error.stack);
            return error.message;
        } else if (error instanceof TosServerError) {
            console.log('Request ID:', error.requestId);
            console.log('Response Status Code:', error.statusCode);
            console.log('Response Err Code:', error.code);
            console.log('Response Err Msg:', error.message);
            return error.message;
        } else {
            console.log('Unexpected exception:', error);
            return error.message;
        }
    }

    /**
     * 上传文件到 TOS
     * @param {Buffer|string} file - 文件内容或文件路径
     * @param {string} key - 文件在 TOS 中的存储路径和文件名
     * @returns {Promise<Object>} - 上传结果
     */
    async uploadFile(file, key) {
        try {
            const result = await this.client.putObject({
                bucket: this.bucket,
                key: key,
                body: file,
            });

            return {
                success: true,
                url: `https://${this.bucket}.tos-cn-beijing.volces.com/${key}`,
                key: key,
                ...result
            };
        } catch (error) {
            const errMsg = this.handleError(error);
            return {
                success: false,
                error: errMsg
            };
        }
    }

    /**
     * 删除 TOS 中的文件
     * @param {string} key - 要删除的文件路径和文件名
     * @returns {Promise<Object>} - 删除结果
     */
    async deleteFile(key) {
        try {
            const result = await this.client.deleteObject({
                bucket: this.bucket,
                key: key,
            });

            return {
                success: true,
                key: key,
                ...result
            };
        } catch (error) {
            const errMsg = this.handleError(error);
            return {
                success: false,
                error: errMsg
            };
        }
    }

    /**
     * 获取文件的临时访问URL
     * @param {string} key - 文件的路径和文件名
     * @param {number} [expires=3600] - URL的有效期（秒）
     * @returns {Promise<string>} - 临时访问URL
     */
    async getSignedUrl(key, expires = 3600) {
        try {
            const url = await this.client.signUrl({
                bucket: this.bucket,
                key: key,
                expires: expires,
            });

            return url;
        } catch (error) {
            const errMsg = this.handleError(error);
            throw new Error(errMsg);
        }
    }

    /**
     * 获取文件信息
     * @param {string} key - 文件的路径和文件名
     * @returns {Promise<Object>} - 文件信息
     */
    async getObjectInfo(key) {
        try {
            const result = await this.client.headObject({
                bucket: this.bucket,
                key: key,
            });

            return {
                success: true,
                data: result.data
            };
        } catch (error) {
            const errMsg = this.handleError(error);
            return {
                success: false,
                error: errMsg
            };
        }
    }
}

module.exports = VolcUploader;
